/**
 *
 */
package cn.dw.mm.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import cn.dw.mm.domain.SelfComment;
import cn.dw.mm.service.FileService;
import cn.dw.mm.utils.FileUtils;
import cn.dw.mm.utils.Resume_Word;

/**
 * @author aubrey
 * @date  上午9:10:41
 * 
 */
@Controller
@RequestMapping("/file")
public class FileUploadController {
	
	@Autowired
	private FileService fileService;
		
	    @RequestMapping("/download")
	    public void downloadSeFile(@RequestParam("fileName") String fileName,HttpServletRequest req ,HttpServletResponse resp) throws IOException {
	    	//先判断特定目录底下是否存在同名的文件
	    	File file = null;
	    	File[] matchFiles = FileUtils.searchFile(new File("E:/springUpload"), fileName);
	    	if (matchFiles.length == 1) {
				file = matchFiles[0];
				FileInputStream fileIn = new FileInputStream(file);
		    	resp.setContentType("application/x-msdownload;");
		    	resp.setHeader("Content-disposition", "attachment; filename="+file.getName());
		    	resp.setHeader("Content-Length", String.valueOf(file.length()));
		    	OutputStream out= resp.getOutputStream();
		    	byte[] buf = new byte[1024];
		    	while(fileIn.read(buf) > 0) {
		    		out.write(buf);
		    	}
		    	out.flush();
		    	out.close();
		    	fileIn.close();
			} else {
				System.out.println("Error! Duplicate files or file not found.");
			}
	    }
	    
	    /*
	     * 删除现场巡察工单对应的支撑材料
	     * */
	    @RequestMapping("/xcxc/delete")
	    @ResponseBody
	    public String deleteXcxcFile(@RequestParam("fileName") String fileName) {
	    	File[] matchFiles = FileUtils.searchFile(new File("E:/springUpload/xcxc"), fileName);
	    	if (matchFiles.length == 1) {
	    		matchFiles[0].delete();
	    		System.out.println("ok");
	    		return "\"success\"";
	    	} else {
	    		System.out.println("not ok");
	    		return "\"fail\"";
			}
	    }
	    
	    /*
	     * 根据文件名下载现场巡察单对应的支撑材料
	     * 
	     * */
	    @RequestMapping("/xcxc/download")
	    public void downloadXcxcFile(@RequestParam("fileName") String fileName,HttpServletRequest req ,HttpServletResponse resp) throws IOException {
	    	System.out.println(fileName);
	    	//先判断特定目录底下是否存在同名的文件
	    	File file = null;
	    	File[] matchFiles = FileUtils.searchFile(new File("E:/springUpload/xcxc"), fileName);
	    	if (matchFiles.length == 1) {
				file = matchFiles[0];
				FileInputStream fileIn = new FileInputStream(file);
		    	resp.setContentType("application/x-msdownload;");
		    	resp.setHeader("Content-disposition", "attachment; filename="+file.getName());
		    	resp.setHeader("Content-Length", String.valueOf(file.length()));
		    	OutputStream out= resp.getOutputStream();
		    	int count = 0;
		    	byte[] buf = new byte[1024];
		    	while((count = fileIn.read(buf)) > 0) {
		    		out.write(buf);
		    	}
		    	out.flush();
		    	out.close();
		    	fileIn.close();
			} else {
				System.out.println("Error! Duplicate files or file not found.");
			}
	    }
	    
	    
	    /*
	     * 上传现场巡察工单对应的支撑材料
	     * */
//	    @RequestMapping("/xcxc/upload")
//	    @ResponseBody
	    public boolean uploadXcxcFile(HttpServletRequest request, String fileName) throws IllegalStateException, IOException
	    {
	        File[] matchFiles = FileUtils.searchFile(new File("E:/springUpload/xcxc/"), fileName);//如果找到同名的文件，报错
	        if (matchFiles.length > 0) {
	        	return false;
			}
	    	//将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
	        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
	                request.getSession().getServletContext());
	        //检查form中是否有enctype="multipart/form-data"
	        if(multipartResolver.isMultipart(request))
	        {
	            //将request变成多部分request
	            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
	           //获取multiRequest 中所有的文件名
	            Iterator iter=multiRequest.getFileNames();
	             
	            while(iter.hasNext())
	            {
	                //一次遍历所有文件
	                MultipartFile file=multiRequest.getFile(iter.next().toString());
	                if(file!=null)
	                {
	                	String tempFileName = file.getOriginalFilename();
	                	String sub = tempFileName.substring(tempFileName.indexOf(".") + 1);//分离出文件后缀名
	                	String filePar = "E:/springUpload/xcxc/";// 文件夹路径  
	                    File myPath = new File(filePar);  
	                    if ( !myPath.exists()){//若此目录不存在，则创建之  
	                        myPath.mkdir();   
	                    }  
	                	String path = filePar + fileName + "." + sub;//路径+文件名+后缀名
	                    //上传
	                    file.transferTo(new File(path));
	                }
	                 
	            }
	           
	        }
	        return true;
	    }
	    
	    //临时用来展示报告的生成，真正实现生成报告的是另外的方法
	    @RequestMapping("/xcbg/download")
	    public void downloadTemp(@RequestParam("fileName") String fileName,HttpServletRequest req ,HttpServletResponse resp) throws IOException {
	    	int result = fileService.download("E:/springUpload/xcbg/", fileName, req, resp);
	    	if (result > 0 ) {
				System.out.println("Download sucessed!");
			} else {
				System.out.println("Download failed!");
			}
	    }
	    @RequestMapping("/xcfa/download")
	    public void downloadTemp2(@RequestParam("fileName") String fileName,HttpServletRequest req ,HttpServletResponse resp) throws IOException {
	    	int result = fileService.download("E:/springUpload/xcfa/", fileName, req, resp);
	    	if (result > 0 ) {
				System.out.println("Download sucessed!");
			} else {
				System.out.println("Download failed!");
			}
	    }
	    @RequestMapping("/xczj/download")
	    public void downloadTemp3(@RequestParam("fileName") String fileName,HttpServletRequest req ,HttpServletResponse resp) throws IOException {
	    	int result = fileService.download("E:/springUpload/xczj/", fileName, req, resp);
	    	if (result > 0 ) {
				System.out.println("Download sucessed!");
			} else {
				System.out.println("Download failed!");
			}
	    }
	    @RequestMapping("/xcjh/download")
	    public void downloadTemp4(@RequestParam("fileName") String fileName,HttpServletRequest req ,HttpServletResponse resp) throws IOException {
	    	int result = fileService.download("E:/springUpload/xcjh/", fileName, req, resp);
	    	if (result > 0 ) {
				System.out.println("Download sucessed!");
			} else {
				System.out.println("Download failed!");
			}
	    }
	    @RequestMapping("/temp/download")
	    public void downloadTemp5(@RequestParam("fileName") String fileName,HttpServletRequest req ,HttpServletResponse resp) throws IOException {
	    	int result = fileService.download("E:/springUpload/temp/", fileName, req, resp);
	    	if (result > 0 ) {
				System.out.println("Download sucessed!");
			} else {
				System.out.println("Download failed!");
			}
	    }
	    
	    /*
	     * 生成表格
	     * */
	    @RequestMapping("/selfComment")
	    public String downloadSelfCommentChart(SelfComment selfComment, HttpServletRequest request,HttpServletResponse response) {
	    	try {
	    		request.setCharacterEncoding("utf-8");
			} catch (Exception e) {
				// TODO: handle exception
			}
	        Map<String,String> map = new HashMap<String,String>();
	        /*Enumeration<String> paramNames = request.getParameterNames();
	        //通过循环将表单参数放入键值对映射中
	        while(paramNames.hasMoreElements()){
	            String key  = paramNames.nextElement();
	            String value = request.getParameter(key);
	            map.put(key, value);
	        }*/
	        //给map填充数据
	        map.put("groupName",selfComment.getGroupName());
	        map.put("name",selfComment.getName());
	        map.put("department",selfComment.getDepartment());
	        map.put("project",selfComment.getProject());
	        map.put("groupWork",selfComment.getGroupWork());
	        map.put("selfCommment",selfComment.getSelfCommment());
	        map.put("groupComment",selfComment.getGroupComment());
	        map.put("rate",selfComment.getRate());
	        map.put("leaderComment",selfComment.getLeaderComment());
	        

	        System.out.println(map);
	        //提示：在调用工具类生成Word文档之前应当检查所有字段是否完整
	        //否则Freemarker的模板引擎在处理时可能会因为找不到值而报错，这里暂时忽略这个步骤
	        File file = null;
	        InputStream fin = null;
	        ServletOutputStream out = null;

	        try{
	            //调用工具类WordGenerator的createDoc方法生成Word文档
	            file = Resume_Word.createDoc(map, "template");
	            fin = new FileInputStream(file);

	            response.setCharacterEncoding("utf-8");
	            response.setContentType("application/msword");
	            response.addHeader("Content-Disposition", "attachment;filename=selfComment.doc");

	            out = response.getOutputStream();
	            byte[] buffer = new byte[1024];//缓冲区
	            int bytesToRead = -1;
	            // 通过循环将读入的Word文件的内容输出到浏览器中  
	            while((bytesToRead = fin.read(buffer)) != -1) {  
	                out.write(buffer, 0, bytesToRead);  
	            }

	        }catch(Exception ex){
	            ex.printStackTrace();
	        }
	        finally{
	            if(fin != null) {
	            	try {
	            		fin.close();  
	            	} catch (Exception e) {
						// TODO: handle exception
					}
	            }
	            if(out != null) {
	            	try {
	            		out.close();  
	            	} catch (Exception e) {
						// TODO: handle exception
					}
	            } 
	            if(file != null) file.delete(); // 删除临时文件  
	        }
	    	return null;
	    }
	    
	    
	    
}

